目前基於Python的量化回測框架有很多,開源框架有zipline、vnpy和backtrader等等,本次以backtrader來示範,
安裝方法可以參考官方網站
簡單的設定
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import backtrader as bt
if __name__ == '__main__':
cerebro = bt.Cerebro()
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
比如說我們要回測SPY狀況
from datetime import datetime
import backtrader as bt
from dateutil.relativedelta import relativedelta
import yfinance as yf
class TestStrategy(bt.Strategy):
def __init__(self):
self._next_buy_date = datetime(2010, 1, 5)
def next(self):
if self.data.datetime.date() >= self. _next_buy_date.date():
self. _next_buy_date += relativedelta(months=1)
self.buy(size=1)
cerebro = bt.Cerebro()
data = bt.feeds.PandasData(dataname=yf.download('SPY', '2015-07-06', '2021-09-23', auto_adjust=True))
cerebro.adddata(data)
cerebro.addstrategy(TestStrategy)
cerebro.broker.set_cash(cash=10000)
cerebro.run()
cerebro.plot()